<?php
/**
 * Created by Jayli.
 * User: Administrator
 * Date: 2018-03-07
 * Time: 14:46
 */

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ShopTypeController extends Controller
{
    protected $api_url = [
        'index' => ['get', 'shop/type'],
        'create'=> ['post', 'shop/type/add'],
        'update'   => ['put', 'shop/type/%d'],
        'delete'   => ['delete', 'shop/type/%d']
    ];

    protected $api_host;
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->api_host = config('url.api_backend');
    }

    public function indexAction()
    {
        $this->validate($this->request, [
            'page' => 'integer',
            'tp_name' => 'string',
        ]);

        $search_params = $this->request->all(['tp_name']);

        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'orderBy' => 'id',
            'sortedBy' => 'desc',
            'page' => $page
        ];
      
        $ret = http_admin($this->api_url['index'])->send($params);

        $data = [];
        if (isset($ret['code']) && $ret['code'] === 0 && !empty($ret['data'])) {
            $data = $ret['data'];
        }

        $data['search_params'] = $search_params;

        return view('Admin.shop.type', paginate($this->request, $data));
    }

    public function createAction(){
        $this->validate($this->request, [
            'tp_name' => 'required|string',
            'tp_status'=>'integer',
        ]);
        $data = $this->request->all([]);

        $ret = http_admin($this->api_url['create'])->send($data);

        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            return response()->json(['code'=>0,'message'=>'']);
        }else{
            return response()->json(['code'=>1,'message'=>isset($ret['message']) ? $ret['message'] : $ret['data']]);
        }
    }

    public function updateAction($id){
        $this->validate($this->request, [
            'tp_name' => 'required|string',
            'tp_status'=>'integer',
        ]);
        $data = $this->request->all([]);

        $ret = http_admin($this->api_url['update'],[$id])->send($data);
        if(isset($ret['code']) && $ret['code']===0 ){
            return response()->json(['code'=>0,'message'=>'']);
        }else{
            return response()->json(['code'=>1,'message'=>$ret['message']]);
        }
    }

    public function deleteAction($id){
        $ret = http_admin($this->api_url['delete'],[$id])->send();
        
        if(isset($ret['code']) && $ret['code']===0){
            return response()->json(['code'=>0,'message'=>$ret['message']]);
        }else{
            return response()->json(['code'=>1,'message'=>$ret['message']]);
        }
    }
}